package com.tddx.activiti.filter.realm;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tddx.activiti.business.sys.entity.systuser.SysTuserEntity;
import com.tddx.activiti.business.sys.service.systuser.SysTuserService;

@Component(value = "authorRealm")
public class AuthorRealm extends AuthorizingRealm {

	@Autowired
	private SysTuserService userService;

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String userName = token.getUsername();
		SysTuserEntity entity = userService.findByVcUsername(userName);
		String vcPass = new String(token.getPassword());
		if (entity!=null&&entity.getVcPass().equals(vcPass)) {
			return new SimpleAuthenticationInfo(
					new Principal(entity)
					, entity.getVcPass()
					, getName());
		}
		return null;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		Set<String> permissions = new HashSet<String>();
		permissions.add("sys:user:view");
		permissions.add("sys:user:edit");
		permissions.add("sys:user:delete");
		authorizationInfo.setStringPermissions(permissions);
		return authorizationInfo;
	}

	public static class Principal implements Serializable {
		
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public Principal(SysTuserEntity user) {
			this.vcUserName = user.getVcUsername();
			this.id = user.getId();
			this.vcName = user.getVcName();
		}

		private long id;
		private String vcUserName;
		private String vcName;

		public long getId() {
			return id;
		}

		public void setId(long id) {
			this.id = id;
		}

		public String getVcUserName() {
			return vcUserName;
		}

		public void setVcUserName(String vcUserName) {
			this.vcUserName = vcUserName;
		}

		public String getVcName() {
			return vcName;
		}

		public void setVcName(String vcName) {
			this.vcName = vcName;
		}

	}

}
